package com.zfp.sys.controller;

import com.zfp.core.controller.BaseController;
import com.zfp.core.plugins.page.Page;
import com.zfp.sys.entity.SysRole;
import com.zfp.sys.entity.SysUser;
import com.zfp.sys.service.SysRoleService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping("sys/sysRole/")
public class SysRoleController extends BaseController {
	@Autowired
	private SysRoleService sysRoleService;

	@RequestMapping("pageList")
	public String pageList(Model model, Page page, SysRole sysRole, HttpSession session){
		SysUser sysUser = (SysUser) session.getAttribute("sessionUser");
		page = sysRoleService.pageList(page,sysRole);
		model.addAttribute("page",page);
		model.addAttribute("sysRole",sysRole);
		model.addAttribute("sysUser",sysUser);
		return "sys/role_list";
	}

	@RequestMapping("edit")
	public String edit(String id,Model model){
		SysRole sysRole = sysRoleService.getById("SysRole.getById",id);
		model.addAttribute("sysRole",sysRole);
		return "sys/sysRole_edit";
	}


	/**
	 * 进入菜单权限受权界面
	 * @param model
	 * @param roleId
	 * @return
	 */
	@RequestMapping("sysRoleMenuEdit")
	public String sysRoleMenuEdit(Model model, String roleId,HttpSession session) {
		SysUser sysUser = (SysUser) session.getAttribute("sessionUser"); //获取用户
		model.addAttribute("zTreeNodes", sysRoleService.getMenuJsonTree(roleId,sysUser));
		model.addAttribute("id", roleId);
		return "sys/sysRole_editMenu";
	}

	/**菜单权限保存
	 * roleMenuSave
	 * @param model
	 * @param roleId,menuIds
	 * @return
	 */
	@RequestMapping("saveRoleMenu")
	public void saveRoleMenu(Model model, PrintWriter out, String roleId, String menuIds) {
		sysRoleService.saveRoleMenuTr(roleId,menuIds);
		out.write("success");
		out.close();
	}

	@RequestMapping("checkRoleNameExist")
	@ResponseBody
	public String checkRoleNameExist(String roleName){
		String msg = "no";
		SysRole sysRole = sysRoleService.getObject("SysRole.checkRoleNameExist",roleName);
		if(sysRole != null){
			msg = "existName";
		}
		return msg;
	}

	@RequestMapping("save")
	@ResponseBody
	public String save(SysRole sysRole,HttpSession session){
		String result = sysRoleService.saveOrUpdate(sysRole,session);
		return result;

	}
	@RequestMapping("findUserRoles")
	@ResponseBody
	public String findUserRoles(HttpSession session){
		SysUser sysUserSession = (SysUser) session.getAttribute("sessionUser");
		List<SysRole> roles = sysRoleService.list("SysRole.findUserRoles",sysUserSession.getUserId());
		JSONArray listArray=JSONArray.fromObject(roles);
		return listArray.toString();
	}
}